<script>
import Container from './components/container'
import Title from './components/title'
import Single from './components/single'
import Input from './components/input'
import Multiple from './components/multiple'
import Select from './components/select'
import Timer from './components/timer'
import Education from './components/education'
import Email from './components/email'
import Gender from './components/gender'
import FileUpload from './components/fileUpload'
import Rule from './components/rule'
import Preview from './components/preview'
import Draggable from 'vuedraggable'
import UUID from 'uuidjs';
import Api from '@/services/commonApi'
// import drag from './utils/drag'
export default {
  data() {
    return {
      previewType: true,
      visible: false,
      modelVisible: false,
      templeteId: '',
      ruleData: null,
      loading: false,
      formTypes: [],
      formData: [],
      drag: false,
      isActive: true,
      dragOption: {
        group: {
          name: 'people',
          pull:'clone'
        }
      }
    }
  },
  
  created() {
    this.init();
  
  },
  mounted() {
    
    
  },
  components: {
    Draggable,
    'q-container': Container,
    'q-single': Single,
    'q-input': Input,
    'q-multiple': Multiple,
    'q-select': Select,
    'q-education': Education,
    'q-timer': Timer,
    'q-email': Email,
    'q-gender': Gender,
    'q-file-upload': FileUpload,
    'q-title': Title,
    'q-rule': Rule,
    'q-preview': Preview
  },
  methods: {

    /**
     * @Description: 初始化模板
     * @param {*}
     * @Date: 2020-10-30 14:14:28
     */    
    init() {
      this.formTypes = [
        {
          title: '基本类型',
          children: [
            {
              itemTitle: '单选题',
              icon: 'icon_type_single',
              formType: 1,
              headerName: '请选择一个选项',
              configDtos: [
                {
                  configName: '选项1',
                  configNumber: 1,
                },
                {
                  configName: '选项2',
                  configNumber: 2,
                },
              ]
            },
            {
              itemTitle: '多选题',
              icon: 'icon_type_multiple',
              formType: 2,
              headerName: '请选择一个选项',
              configDtos: [
                {
                  configName: '选项1',
                  configNumber: 1,
                },
                {
                  configName: '选项2',
                  configNumber: 2,
                },
              ]
            },
            {
              itemTitle: '下拉题',
              icon: 'icon_type_selete',
              formType: 3,
              headerName: '请选择一个选择框选项',
              configDtos: [
                {
                  configName: '选项1',
                  configNumber: 1,
                  icon: ''
                },
                {
                  configName: '选项2',
                  configNumber: 2,
                  icon: ''
                },
              ]
            },
            {
              itemTitle: '填空题',
              icon: 'icon_type_input',
              formType: 4,
              headerName: '请填写本项内容'
            },
          ]
        },
        {
          title: '常用题型',
          children: [
            {
              itemTitle: 'Email',
              icon: 'icon_type_email',
              formType: 100,
              headerName: '邮箱'
            },
            {
              itemTitle: '性别',
              icon: 'icon_type_gender',
              formType: 101,
              headerName: '性别',
              configDtos: [
                {
                  configName: '男',
                  configNumber: 1,
                  icon: ''
                },
                {
                  configName: '女',
                  configNumber: 2,
                  icon: ''
                },
              ]
            },
            {
              itemTitle: '学历',
              icon: 'icon_type_education',
              formType: 102,
              headerName: '您的最高学历（含目前在读）是？',
              configDtos: [
                {
                  configName: '小学及以下',
                  configNumber: 1,
                  icon: ''
                },
                {
                  configName: '初中',
                  configNumber: 2,
                  icon: ''
                },
                {
                  configName: '高中/中专/技校',
                  configNumber: 3,
                  icon: ''
                },
                {
                  configName: '大学专科',
                  configNumber: 4,
                  icon: ''
                },
                {
                  configName: '大学本科',
                  configNumber: 5,
                  icon: ''
                },
                {
                  configName: '硕士研究生及以上',
                  configNumber: 6,
                  icon: ''
                }
              ]
            },
            {
              itemTitle: '时间',
              icon: 'icon_type_timer',
              formType: 103,
              headerName: '时间'
            },
          ]
        },
        {
          title: '其他题型',
          children: [
            {
              itemTitle: '文件上传',
              icon: 'icon_type_file_upload',
              formType: 200,
              headerName: '请上传文件'
            }
          ]
        }
      ]
      this.formData = [{
        formType: 0,
        headerName: '问卷标题',
        desc: '感谢您能抽出几分钟时间来参加本次答题'
      }]
    },
    /**
     * @Description: 拖拽防止放在标题前面
     * @param {*}
     * @Date: 2020-10-30 09:01:36
     */    
    dealOrderFormData() {
      this.formData = this.formData.filter(item => {
        return item.formType != 0
      });
      this.formData.unshift({
        formType: 0,
        headerName: '问卷标题',
        desc: '感谢您能抽出几分钟时间来参加本次答题'
      })
    },

    /**
     * @Description: 根据type返回component
     * @param {*}
     * @Date: 2020-10-27 15:20:45
     */
    getComponent(data) {
      switch (data.formType) {
        case 0:
          return <q-title data={data}></q-title>;
        case 1:
          return <q-single data={data} onChangeOp={this.changeOperation}></q-single>;
        case 2:
          return <q-multiple data={data} onChangeOp={this.changeOperation}></q-multiple>;
        case 3:
          return <q-select data={data} onChangeOp={this.changeOperation}></q-select>;
        case 4:
          return <q-input data={data}></q-input>;
        case 100:
          return <q-email data={data}></q-email>;
        case 101:
          return <q-gender data={data} onChangeOp={this.changeOperation}></q-gender>;
        case 102:
          return <q-education data={data} onChangeOp={this.changeOperation}></q-education>;
        case 103:
          return <q-timer data={data} ></q-timer>;
        case 200:
          return <q-file-upload data={data} ></q-file-upload>;
        default:
          break;
      }
      return null;
    },

    /**
     * @Description: 渲染左侧内容
     * @param {*}
     * @Date: 2020-10-27 15:14:06
     */ 

    renderLeftFormType() {
      const {formTypes} = this
      return formTypes.map((item, index) => {
        return (
          <dl class="form-type-warp" key={index}>
            <dt>{item.title}</dt>
            <dd class="form-items">
              <draggable 
                v-model={item.children} 
                options={this.dragOption} 
                onStart={this.onStart} 
                onEnd={this.leftEnd} 
                onAdd={this.leftAdd}
                forceFallback="true"  
                animation="500"
                move={this.leftMove}
              >
                <transition-group>
                  {
                    ...item.children.map((it,i) => {
                      return(
                        <div class="form-item" onClick={() => this.formItemClick(it)} key={i}>
                          <i class={['icon_wj'+' ' + it.icon]}></i>
                          {it.itemTitle}
                        </div>
                      );
                    })
                  }
                </transition-group>
              </draggable>
            </dd>
          </dl>
        );
      })
    },

    /**
     * @Description: 渲染右侧区域
     * @param {*}
     * @Date: 2020-10-27 15:14:58
     */    
    renderRightFormType() {
      const {formData} = this;
      return (
        <draggable 
          v-model={this.formData} 
          onStart={this.onStart} 
          end={this.onEnd1} 
          move={this.rightMove}
          forceFallback="true" 
          group="people"
          animation="1000"
          handle=".mover"
        >
          <transition-group>
          {
            formData.map((item, index) => {
              return (
                <q-container 
                  key={index} 
                  order={index} 
                  isTitle={index === 0 ? true : false}
                  onDelItem={() => this.handleDelItem(index)}
                  ruleOptionClick={() => this.handleClickContainer(item, index)}
                >
                  {this.getComponent(item)}
                </q-container>
              );
            })
          }
          </transition-group>
        </draggable>
      );
    },

    onStart() {
      
    },

    leftEnd() {
      this.formData = JSON.parse(JSON.stringify(this.formData))
      if(this.formData[0].formType != 0) {
        this.dealOrderFormData();
      }
    },
    
    leftAdd() {

    },

    leftMove(e,originalEvent) {
      
      if(originalEvent.target.id !== 'container') {
        return false
      }

      // if(e.relatedContext.element.formType === 0) {
      //   return false
      // }

      return true
    },

    onEnd1() {
      // console.log(e)
    },

    /**
     * @Description: 右侧渲染区域拖拽move
     * @param {*}
     * @Date: 2020-10-29 08:55:23
     */    
    rightMove(e) {
      if(e.draggedContext.element.formType === 0) {
        return false
      }
      if(e.relatedContext.element.formType === 0) {
        return false
      }
      return true
    },

    /**
     * @Description: options项顺序发生变化时
     * @param {*}
     * @Date: 2020-10-29 15:56:55
     */    
    changeOperation(index, options) {
      
      this.formData[index].configDtos = options
    },

    /**
     * @Description: 表单类型点击时触发的事件
     * @param {*} value
     * @Date: 2020-10-27 15:14:22
     */
    
    formItemClick(value) {
      const formItem = this.initFormData(value)
      this.formData.push(formItem)
    },

    /**
     * @Description: 初始化表单数据
     * @param {*}
     * @Date: 2020-10-29 09:24:12
     */    
    initFormData(value) {
      let obj = {}
      Object.keys(value).forEach(key => {
        if(key !== 'itemTitle' && key !== 'icon') {
          obj[key] = value[key]
        }
      })
      return obj
    },

    /**
     * @Description: 删除单个的表单控件
     * @param {*}
     * @Date: 2020-10-27 15:38:48
     */    
    handleDelItem(val) {
      this.formData.splice(val, 1);
    },

    /**
     * @Description: 保存并发布
     * @param {*}
     * @Date: 2020-10-28 15:44:36
     */    
    handleSaveClick() {
      const previewData = this.dealFormData(false);
      previewData.status = 1
      previewData.deleteFlag = 0
      this.loading = true
      Api.post('app/center/inner/template/addTemplate', previewData).then(res => {
        if(res.data.code != 200) {
          this.$message.error('保存失败，'+res.data.message)
        } else {
          this.$message.success('保存成功！')
          this.init();
        }
      }).finally(() => {
        this.loading = false
      })
    },

    /**
     * @Description: 预览
     * @param {*}
     * @Date: 2020-10-28 15:46:05
     */    
    handlePreview() {
      // const previewData = this.dealFormData();
      // console.log('previewData', previewData)
      // this.$router.push({name: '模板预览', params: previewData, query: {id: UUID.generate()}})
      // this.$router.push({name: 'questionnaire', params: previewData, query: {id: UUID.generate()}})
      this.modelVisible = true
    },

    /**
     * @Description: 处理表单数据
     * @param {*}
     * @Date: 2020-10-30 09:02:26
     */    
    dealFormData(isId = true) {
      let tempFormData = JSON.parse(JSON.stringify(this.formData))
      let result = {headerDtos: []}
      tempFormData.forEach((item, index) => {
        isId ? item.id = UUID.generate() : null
        if(index === 0) {
          result.titleName = item.headerName
          result.headline = item.desc
        } else {
          item.headerNumber = index
          if(!item.ruleOption) {
            item.ruleOption = {}
          }
          const tempItem = this.initFormData(item)
          result.headerDtos.push(tempItem)
        }
      })
      return result
    },

    handleClickContainer(value, index) {
      if(!index) {
        return null
      }
      this.ruleData = {
        index,
        value
      }
      this.visible = true
    },

    onClose() {
      this.visible = false
    },

    modelCancel() {
      this.modelVisible = false
    },

    handleCancel() {
      this.previewType = true
    },

    handleOk() {
      this.previewType = false
      this.isActive = false
    }
  },
  render() {
    return(
      <div id="questionnaire">
        <div class="top">
          <a-button type="primary" style="margin-right: 20px" onClick={this.handlePreview}>
            预览
          </a-button>
          <a-button loading={this.loading} type="primary" onClick={this.handleSaveClick}>
            保存
          </a-button>
        </div>
        <div class="content">
          <div class="left-warp">
          {...this.renderLeftFormType()}
          </div>
          <div class="right-warp">
            {this.renderRightFormType()}
          </div>
        </div>
        <a-drawer
          title="题目设置"
          placement="right"
          visible={this.visible}
          destroyOnClose={true}
          maskClosable
          width="300"
          onClose={this.onClose}
        >
          <q-rule data={this.ruleData}></q-rule>
        </a-drawer>
        <a-modal 
          visible={this.modelVisible} 
          title="模板预览" 
          destroyOnClose={true}
          width={700}
          cancelText="iphone版"
          okText="pc版"
          onCancel={this.modelCancel}
        >
          <q-preview templateData={this.dealFormData()} isPc={this.previewType}></q-preview>
          <template slot="footer">
            <a-button key="back" onclick={this.handleCancel} class={this.isActive ? 'active' : null}>
              pc版
            </a-button>
            <a-button key="submit" onClick={this.handleOk}>
              iphone版
            </a-button>
          </template>
        </a-modal>
      </div>
    );
  }
}
</script>

<style lang="less">
  .active {
    color: #13c2c2;
    // background-color: #fff;
    border-color: #13c2c2;
  }
  #questionnaire{
    // background-color: #fff;
    padding-top: 20px;
    .top {
      width: 100%;
      height: 50px;
      background-color: #fff;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding-right: 30px;
    }
    .content {
      display: flex;
      background-color: #fff;
      .left-warp {
        max-width: 27%;
        // height: 100vh;
        border-right: 1px solid #aaa;
        padding: 15px 0 15px 15px;
        // position: relative;
        .form-type-warp {
          .form-items {
            display: flex;
            flex-wrap: wrap;
            margin-top: 10px;
            span {
              display: flex;
              flex-wrap: wrap;
            }
            .form-item {
              border: 1px solid #aaa;
              height: 30px;
              width: 130px;
              margin:0 10px 10px 0;
              border-radius: 1px;
              // text-align: center;
              padding-left: 25px;
              line-height: 30px;
              cursor: pointer;
              .icon_wj {
                display: inline-block;
                width: 24px;
                height: 24px;
                background: url(https://s1.wenjuan.com/static/images/icon_edit_question.png!90q.webp?v=20190830) no-repeat;
                background-size: 135px;
                vertical-align: top;
                margin: 3px;
              }
              .icon_type_single {
                background-position: -8px -7px;
              }
              .icon_type_multiple {
                background-position: -36px -7px
              }
              .icon_type_email {
                background-position: -8px -196px;
              }
              .icon_type_file_upload {
                background-position: -8px -321px;
              }
              .icon_type_gender {
                background-position: -36px -196px;
              }
              .icon_type_selete {
                background-position: -8px -135px;
              }
              .icon_type_education {
                background-position: -36px -512px;
              }
              .icon_type_timer {
                background-position: -36px -260px;
              }
              .icon_type_input {
                background-position: -8px -39px;
              }
              &:hover {
                border-color: blue;
                border-width: 2px;
                // color: blue;
              }
            }
          }
        }
      }
      .right-warp {
        // width: 70%;
        padding: 15px 0 15px 15px;
        min-height: 100vh;
      }
    }
  }
</style>